package cn.ransj.animation.util;

import java.util.ArrayList;
import java.util.HashMap;

import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationSet;

/**
 * animation connector to connect a list of animations
 * 
 * @author android
 * 
 */
public class AniConnector implements AnimationListener, AniConnectorInterface {
	private static final int STATE_START = 0;
	private static final int STATE_END = 1;
	private ArrayList<Animation> mAnims;
	private HashMap<Integer, Integer> mRepeatMap;
	private View mView;
	private int mCurrRepeatNum;
	private AniCoonectorListener mStateListener;
	
	public AniConnector(){
		this(null);
	}

	public AniConnector(ArrayList<Animation> animations) {
		this(animations, null);
	}

	public AniConnector(ArrayList<Animation> animations,
			HashMap<Integer, Integer> repeatMap) {
		mAnims = animations;
		mRepeatMap = repeatMap;
	}

	public void setAnimations(ArrayList<Animation> animations) {
		setAnimations(animations, null);
	}

	public void setAnimations(ArrayList<Animation> animations,
			HashMap<Integer, Integer> repeatMap) {
		mAnims = animations;
		mRepeatMap = repeatMap;

	}

	public void start(View view) {
		if(view == null || mAnims == null || mAnims.isEmpty()){
			return;
		}
		mView = view;
		Animation set = mAnims.get(0);
		set.setAnimationListener(this);
		if(mRepeatMap != null && mRepeatMap.containsKey(0)){
			mCurrRepeatNum = mRepeatMap.get(0);
		}
		notifyStateChange(STATE_START);
		mView.setAnimation(set);
	}
	
	public void destory(){
		mCurrRepeatNum = -1;
		mRepeatMap = null;
		mAnims.clear();
		mView = null;
	}

	public void onAnimationEnd(Animation animation) {
		nextAni(animation);
	}

	public void onAnimationRepeat(Animation animation) {

	}

	public void onAnimationStart(Animation animation) {

	}
	
	private void nextAni(Animation ani){
		if (mCurrRepeatNum > 0) {
			mCurrRepeatNum --;
			mView.startAnimation(ani);
		}else{
			int index = mAnims.indexOf(ani);
			if (index != -1) {
				index++;
				if(index != mAnims.size()){
					Animation next = mAnims.get(index);
					next.setAnimationListener(this);
					if(mRepeatMap != null && mRepeatMap.containsKey(index)){
						mCurrRepeatNum = mRepeatMap.get(index);
					}
					mView.setAnimation(next);
				}else{
					notifyStateChange(STATE_END);
				}
			}
		}
	}

	public void setAniConnectorListener(AniCoonectorListener listener) {
		mStateListener = listener;
	}
	
	private void notifyStateChange(int state){
		if(mStateListener != null){
			switch(state){
			case STATE_START:
				mStateListener.onAnimationStart(this);
				break;
			case STATE_END:
				mStateListener.onAnimationEnd(this);
				break;
			}
		}
	}
	
}
